package com.project.mq.mqserver;

import com.project.mq.common.*;
import com.project.mq.mqserver.core.BasicProperties;
import com.project.mq.common.Consumer;
import lombok.Data;

import java.io.*;
import java.net.ServerSocket;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import static com.fasterxml.jackson.databind.type.LogicalType.Map;


/**
 *
 */
@Data
public class BrokerServer {
    // 当前程序只考虑一个虚拟主机的情况。
    private VirtualHost virtualHost = new VirtualHost("default-VirtualHost");
    // key 为 channelId，value 为 channel 对应的 socket 对象。
    // 使用这个 哈希表 表示当前的所有会话 (也就是说有那些客户端正在和咱们的服务器进行通信)
    private ConcurrentHashMap<String, Socket> sessions = new ConcurrentHashMap<>();
    private ServerSocket serverSocket = null;
    //引入线程池来处理多个客户端的请求
    private ExecutorService executorService = null;
    //引入一个boolean控制服务器是否继续运行
    private volatile boolean runnable = true;

    public BrokerServer(int port) throws IOException {
        serverSocket = new ServerSocket(port);
    }

    public void start() throws IOException {
        System.out.println("[BrokerServer] 启动完成!");
        executorService = Executors.newCachedThreadPool();
        try {
            while (runnable) {
                //接受一个客户端的连接请求
                Socket clientSocket = serverSocket.accept();
                //把处理连接这个任务直接丢给线程池
                executorService.submit(() -> processConnection(clientSocket));
            }
        } catch (SocketException e) {
            System.out.println("[BrokerServer] 服务器关闭完成!");
        }
    }

    // 一般来说停止服务器，就是直接 kill 掉对应进程就行了。
    // 此处还是搞一个单独的停止方法，主要是用于后续的单元测试。
    public void stop() throws IOException {
        runnable = false;
        // 立即结束所有的线程池的任务
        executorService.shutdownNow();
        serverSocket.close();
    }

    //通过这个方法来处理一个客户端的连接
    //在这个连接中,可能会涉及多个请求和响应
    private void processConnection(Socket clientSocket) {
        try (InputStream inputStream = clientSocket.getInputStream();
             OutputStream outputStream = clientSocket.getOutputStream()) {
            // 这里需要按照特定格式来读取并解析，此时就需要用到 DataInputStream 和 DataOutputStream
            try (DataInputStream dataInputStream = new DataInputStream(inputStream);
                 DataOutputStream dataOutputStream = new DataOutputStream(outputStream)) {
                while (true) {
                    //1.读取请求并解析
                    Request request = readRequest(dataInputStream);
                    //2.根据请求计算响应
                    Response response = process(request, clientSocket);
                    //3.响应写回客户端
                    writeResponse(dataOutputStream, response);
                }
            }

        } catch (EOFException | SocketException e) {
            // 对于这个代码，DataInputStream 如果读到 EOF ，就会抛出一个 EOFException 异常.
            // 需要借助这个异常来结束循环
            System.out.println("[BrokerServer] connection 关闭！客户端的地址：" + clientSocket.getInetAddress().toString()
                    + ":" + clientSocket.getPort());
        } catch (IOException | MqException | ClassNotFoundException e) {
            System.out.println("[BrokerServer] connection 出现异常!");
            e.printStackTrace();
        } finally {
            try {
                //连接处理完记得关闭socket对象
                clientSocket.close();
                // 对 sessions 进行清理
                // 一个 TCP 连接中，可能包含多个 channel. 需要把当前这个 socket 对应的所有 channel 也顺便清理掉.
                clearClosedSession(clientSocket);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    private void clearClosedSession(Socket clientSocket) {
        // 这里不要在同一个循环中，同时进行遍历 + 删除操作。否则可能有迭代器失效问题。
        // 拆成两个循环来处理是更合适的。
        List<String> toDeleteChannelId = new ArrayList<>();
        for (Map.Entry<String, Socket> entry : sessions.entrySet()) {
            if (entry.getValue() == clientSocket) {
                toDeleteChannelId.add(entry.getKey());
            }
        }
        for (String channelId : toDeleteChannelId) {
            sessions.remove(channelId);
        }
        System.out.println("[BrokerServer] 清理 session 完成！被清理的 channelId=" + toDeleteChannelId);
    }

    private void writeResponse(DataOutputStream dataOutputStream, Response response) throws IOException {
        dataOutputStream.writeInt(response.getType());
        dataOutputStream.writeInt(response.getLength());
        dataOutputStream.write(response.getPayload());
        //刷新缓存区
        dataOutputStream.flush();
    }

    private Response process(Request request, Socket clientSocket) throws MqException, IOException, ClassNotFoundException {
        // 1. 从request中解析出业务请求
        BaseArguments baseArguments = (BaseArguments) BinaryTool.fromBytes(request.getPayload());
        System.out.println("[Request] rid=" + baseArguments.getRid() + ", channelId=" + baseArguments.getChannelId() + ", type=" + request.getType() + ", length=" + request.getLength());

        // 2. 根据type来区分业务分支。
        boolean ok = true;
        if (request.getType() == 0x1) {
            // 创建channel
            sessions.put(baseArguments.getChannelId(), clientSocket);
            System.out.println("[BrokerServer] 创建channel完成! channelId=" + baseArguments.getChannelId());
        } else if (request.getType() == 0x2) {
            // 销毁channel
            sessions.remove(baseArguments.getChannelId());
            System.out.println("[BrokerServer] 销毁channel完成! channelId=" + baseArguments.getChannelId());
        } else if (request.getType() == 0x3) {
            // 创建交换机
            ExchangeDeclareArguments exchangeDeclareArguments = (ExchangeDeclareArguments) baseArguments;
            ok = virtualHost.exchangeDeclare(exchangeDeclareArguments.getExchangeName(), exchangeDeclareArguments.getExchangeType(), exchangeDeclareArguments.isDurable(), exchangeDeclareArguments.isAutoDelete(), exchangeDeclareArguments.getArguments());
        } else if (request.getType() == 0x4) {
            // 删除交换机
            ExchangeDeleteArguments exchangeDeleteArguments = (ExchangeDeleteArguments) baseArguments;
            ok = virtualHost.exchangeDelete(exchangeDeleteArguments.getExchangeName());
        } else if (request.getType() == 0x5) {
            // 创建队列
            QueueDeclareArguments queueDeclareArguments = (QueueDeclareArguments) baseArguments;
            ok = virtualHost.queueDeclare(queueDeclareArguments.getQueueName(), queueDeclareArguments.isDurable(), queueDeclareArguments.isExclusive(), queueDeclareArguments.isAutoDelete(), queueDeclareArguments.getArguments());
        } else if (request.getType() == 0x6) {
            // 删除队列
            QueueDeleteArguments queueDeleteArguments = (QueueDeleteArguments) baseArguments;
            ok = virtualHost.queueDelete(queueDeleteArguments.getQueueName());
        } else if (request.getType() == 0x7) {
            // 创建绑定
            QueueBindArguments queueBindArguments = (QueueBindArguments) baseArguments;
            ok = virtualHost.queueBind(queueBindArguments.getQueueName(), queueBindArguments.getExchangeName(), queueBindArguments.getBindingKey());
        } else if (request.getType() == 0x8) {
            // 解除绑定
            QueueUnbindArguments queueUnbindArguments = (QueueUnbindArguments) baseArguments;
            ok = virtualHost.queueUnbind(queueUnbindArguments.getQueueName(), queueUnbindArguments.getExchangeName());
        } else if (request.getType() == 0x9) {
            // 发送消息
            BasicPublishArguments basicPublishArguments = (BasicPublishArguments) baseArguments;
            ok = virtualHost.basicPublish(basicPublishArguments.getExchangeName(), basicPublishArguments.getRoutingKey(), basicPublishArguments.getBasicProperties(), basicPublishArguments.getBody());
        } else if (request.getType() == 0xa) {
            // 订阅消息
            BasicConsumeArguments basicConsumeArguments = (BasicConsumeArguments) baseArguments;
            // 创建个回调，用来把消费的数据转发回客户端。
            ok = virtualHost.basicConsume(basicConsumeArguments.getConsumeTag(), basicConsumeArguments.getQueueName(), basicConsumeArguments.isAutoAck(), new Consumer() {
                // 这个回调函数要做的工作，就是把服务器收到的消息可以直接推送回对应的消费者客户端
                @Override
                public void handleDelivery(String consumerTag, BasicProperties properties, byte[] body) throws MqException, IOException {
                    // 1. 根据channelId找到对应的socket
                    //// 先知道当前这个收到的消息，要发给哪个客户端。
                    //// 此处 consumerTag 其实是 channelId。根据 channelId 去 sessions 中查询，就可以得到对应的
                    //// socket 对象了，从而可以往里面发送数据了
                    Socket clientSocket = sessions.get(consumerTag);
                    if (clientSocket == null || clientSocket.isClosed()) {
                        throw new MqException("[BrokerServer] 订阅消息的客户端已经关闭!");
                    }
                    // 2. 构造响应数据
                    SubscribeReturns subScribeReturns = new SubscribeReturns();
                    subScribeReturns.setChannelId(consumerTag);
                    subScribeReturns.setRid(""); // 由于这里只有响应，没有请求，不需要去对应。rid 暂时不需要。
                    subScribeReturns.setOk(true);
                    subScribeReturns.setConsumerTag(consumerTag);
                    subScribeReturns.setBasicProperties(properties);
                    subScribeReturns.setBody(body);
                    byte[] payload = BinaryTool.toBytes(subScribeReturns);
                    // 3. 写入到对应 socket 中
                    Response response = new Response();
                    response.setType(0xc);
                    // response 的 payload 就是一个 SubScribeReturns
                    response.setLength(payload.length);
                    response.setPayload(payload);
                    // 此处不应该关闭 DataOutputStream，关闭这个会导致内部持有的 clientSocket.getOutputStream 被关闭。
                    //此时无法继续往socket中持续写入数据
                    DataOutputStream dataOutputStream = new DataOutputStream(clientSocket.getOutputStream());
                    writeResponse(dataOutputStream, response);
                }
            });
        } else if (request.getType() == 0xb) {
            // 确认 ack
            BasicAckArguments basicAckArguments = (BasicAckArguments) baseArguments;
            ok = virtualHost.basicAck(basicAckArguments.getQueueName(), basicAckArguments.getMessageId());
        } else {
            throw new MqException("[BrokerServer] 未知的请求 type ! type=" + request.getType());
        }

        // 3. 构造响应。
        BaseReturns baseReturns = new BaseReturns();
        baseReturns.setRid(baseArguments.getRid());
        baseReturns.setChannelId(baseArguments.getChannelId());
        baseReturns.setOk(ok);

        byte[] payload = BinaryTool.toBytes(baseReturns);
        Response response = new Response();
        response.setType(request.getType());
        response.setLength(payload.length);
        response.setPayload(payload);
        System.out.println("[Response] rid=" + baseReturns.getRid() + ", channelId=" + baseReturns.getChannelId() + ", type=" + response.getType() + ", length=" + response.getLength());
        return response;
    }

    private Request readRequest(DataInputStream dataInputStream) throws IOException{

        Request request = new Request();
        request.setType(dataInputStream.readInt());
        request.setLength(dataInputStream.readInt());
        byte[] payload = new byte[request.getLength()];
        int n = dataInputStream.read(payload);
        if (n != request.getLength()) {
            throw new IOException("读取请求数据出错!");
        }
        request.setPayload(payload);
        return request;
    }
}
